chrome.sidePanel
  .setPanelBehavior({
    openPanelOnActionClick: true
  })
  .then(() => {
    // ignore
    console.log("chrome.sidePanel已加载")
  })
  .catch((error) => console.log(error))

// 当前tab 改变时触发，例如刷新当前页
chrome.tabs.onUpdated.addListener(async (tabId, info, tab) => {
  if (tab)
    if (tab.url) {
      tabUpdateChangeSendMessage(tab.url)
    }
})

// tab页签切换时触发
chrome.tabs.onActivated.addListener((activeInfo) => {
  // 获取当前页签信息
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (tabs.length > 0) {
      tabUpdateChangeSendMessage(tabs[0].url)
    }
  })
})

// 通知订阅端tab页签切换了
const tabUpdateChangeSendMessage = (tabUrl) => {
  const domain = new URL(tabUrl).origin

  chrome.runtime.sendMessage({
    type: "changeTab",
    data: domain
  })
}

// 消息接收中心，通过type来对各种消息做处理
chrome.runtime.onMessage.addListener(async (message) => {
  console.log("我是background,我接收了")
  console.log(message, "message")
  if (message.type === "SSOLogin") {
    const [tab] = await chrome.tabs.query({
      active: true,
      lastFocusedWindow: true
    })
    const response = await chrome.tabs.sendMessage(tab.id, {
      type: "SSOLogin1"
    })
  }
})

// 创建右键菜单项
chrome.contextMenus.create({
  title: "AI智能助手",
  id: "saveNote",
  contexts: ["all", "page"]
})

// 右键菜单项被点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.sidePanel.open({ windowId: tab.windowId }).then(() => {
    setTimeout(() => {
      tabUpdateChangeSendMessage(tab.url)
    }, 1000)
  })
})
